import Vue from 'vue'
import ajax from '@U/ajax'
Vue.use(ajax)

var user = {
  userLogin: function (formdata, checked, hideLoad, showTip,success) {
    var self = this;
    self.clear();
    ajax.postStream('/admin/auth/common/authUser/login.do', {
      data: formdata,
      success: function (res) {
        hideLoad()
        if (res.success) {
          let data = res.object || {}
          
          if (checked) {
            for (let key in res.data) {
              localStorage.setItem(key, res.data[key])
            }
            localStorage.setItem('account', formdata.account)
            localStorage.setItem('passwd', formdata.passwd)
          } else {
            localStorage.removeItem('account')
            localStorage.removeItem('passwd')
          } 

          self.setItem("name",data.userName);
          self.setItem("id",data.userId);
          self.setItem("sessionKey",data.sessionKey);
          self.setItem("toggle",data.toggle);

          success && success(data);
        } else {
          showTip(res.message, 'error')
        }
      },
      error: () => {
        hideLoad()
        if (!window.navigator.onLine) {
          showTip('网络连接失败', 'error')
        }
      }
    })
  },
  setItem(key,value){
    var userInfo = {};
    try{
      userInfo = JSON.parse(sessionStorage.getItem("UserInfo")) || {};
    }catch(e){}
    userInfo[key] = value;
    sessionStorage.setItem("UserInfo",JSON.stringify(userInfo));
  },
  getItem(key,def){
    var userInfo = {};
    try{
      userInfo = JSON.parse(sessionStorage.getItem("UserInfo")) || {};
    }catch(e){}
    return userInfo[key] || def;
  },
  get(){
    var userInfo = {};
    try{
      userInfo = JSON.parse(sessionStorage.getItem("UserInfo")) || {};
    }catch(e){}
    return userInfo;
  },
  logout(success) {
    var self = this;
    self.clear();
    success && success();
  },
  clear: function () {
    sessionStorage.removeItem('UserInfo')
  }
}

export default user
